package org.alvin.mp3.download;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

/**
 * 弄歌宝
 */
public class GequbaoDownload implements IDownload {
    @Override
    public void download(String search, String downloadDir, JTextArea textArea) throws IOException, InterruptedException {
        textArea.setText("");
        textArea.append("弄歌宝开始下载");
        textArea.append("\n");
        String[] lines = search.trim().split("\n");
        for (String line : lines) {
            downloadMp3(line.trim(), downloadDir, textArea);
            textArea.append("等待===防止IP被禁止");
            textArea.append("\n");
            TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
            textArea.append("等待完成");
            textArea.append("\n");
        }
    }

    public void downloadMp3(String name, String downloadDir, JTextArea textArea) throws IOException, InterruptedException {
        textArea.append("弄歌宝---搜索内容：" + name);
        textArea.append("\n");
        String url = "https://www.gequbao.com/s/";
        url = url + URLEncoder.encode(name, "utf-8");

        Document rootDocument = Jsoup.connect(url).get();
        Elements elements = rootDocument.getElementsByClass("card mb-1");
        if (elements.isEmpty()) {
            return;
        }
        elements = elements.get(0).getElementsByClass("card-text");
        if (elements.isEmpty()) {
            return;
        }
        elements = elements.get(0).getElementsByClass("row");
        for (int i = 1; i < elements.size(); i++) {
            textArea.append("等待===防止IP被禁止");
            textArea.append("\n");
            TimeUnit.SECONDS.sleep((long) (Math.random() * 10));
            textArea.append("等待完成");
            textArea.append("\n");
            Element el = elements.get(i);
            Elements aels = el.getElementsByTag("a");
            String href = aels.get(0).attr("href");
            System.out.println(href);

            url = "https://www.gequbao.com" + href;
            Document document = Jsoup.connect(url).get();
//            Element downloadMp3 = document.getElementById("btn-download-mp3");
            String text = document.toString();
            int index = text.indexOf("window.play_id");
            System.out.println(index);
            String id = text.substring(index);
            index = id.indexOf(";");
            id = id.substring(0, index);
            id = id.substring(id.indexOf("'") + 1, id.lastIndexOf("'"));
            //标题
            index = text.indexOf("window.mp3_title");
            String title = text.substring(index);
            index = title.indexOf(";");
            title = title.substring(0, index);
            title = title.substring(title.indexOf("'") + 1, title.lastIndexOf("'"));
            //作者
            index = text.indexOf("window.mp3_author");
            String author = text.substring(index);
            index = author.indexOf(";");
            author = author.substring(0, index);
            author = author.substring(author.indexOf("'") + 1, author.lastIndexOf("'"));

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", id);
            String rpcResult = HttpRequest.post("https://www.gequbao.com/api/play-url")
                    .header("Content-Type", "application/json")
                    .body(jsonObject.toString())
                    .execute()
                    .body();
            if (rpcResult.indexOf("Too Many Requests") != -1) {
                textArea.append("请求太频繁");
                textArea.append("\n");
                i--;
                continue;
            }
            File file = new File(downloadDir);
            file.mkdirs();
            try {
                JSONObject res = JSONObject.parseObject(rpcResult);
                if (res.getIntValue("code") == 1) {
                    res = res.getJSONObject("data");
                    String mp3Url = res.getString("url");
                    try {
                        id = id.replaceAll("[\\\\/:*?\"<>|]", "");
                        title = title.replaceAll("[\\\\/:*?\"<>|]", "");
                        author = author.replaceAll("[\\\\/:*?\"<>|]", "");
                        //下载mp3
                        HttpUtil.downloadFile(mp3Url, new File(downloadDir, id + "==" + title + "-" + author + ".mp3"));
                        String console = "下载mp3:" + title + "-" + author + ".mp3";
                        textArea.append(console);
                        textArea.append("\n");
                        //下载歌词
                        String lrc = document.getElementById("content-lrc").text();
                        Files.write(Paths.get(file.getAbsolutePath(), id + "==" + title + "-" + author + ".lrc"), lrc.replaceAll("\\[", "\n[").getBytes());
                        console = "下载歌词：" + title + "-" + author + ".lrc";
                        textArea.append(console);
                        textArea.append("\n");
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
